package com.chezhujie.www.controller;

import com.chezhujie.www.domain.Czjawarduse;
import com.chezhujie.www.domain.Czjbusiness;
import com.chezhujie.www.domain.Czjorder;
import com.chezhujie.www.domain.Czjrefund;
import com.chezhujie.www.enums.OrderStatus;
import com.chezhujie.www.enums.RefundStatus;
import com.chezhujie.www.service.*;
import com.sys.core.page.Pagination;
import com.sys.core.utils.ConvertObj;
import com.sys.core.utils.UUIDUtils;
import com.sys.user.base.controller.BaseController;
import com.sys.user.domain.Xyuser;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import weixin.popular.bean.paymch.SecapiPayRefundResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.*;

/**
 *   退款记录表
 * Created by 汤伟杰 on 2017/5/23.
 */
@Controller
@RequestMapping("/czjrefund")
public class CzjrefundController extends BaseController<Czjrefund> {
    @Autowired
    private CzjrefundService czjrefundService;
    @Autowired
    private CzjorderService czjorderService;
    @Autowired
    private CzjbusinessService czjbusinessService;
    @Autowired
    private WeixininfoService weixininfoService;
    @Autowired
    private CzjawarduseService czjawarduseService;

    /** 列表详情页 **/
    @RequestMapping("/listdetail.do")
    public String listdetail(Integer pageNo, Integer pageSize, Czjrefund czjrefund, HttpSession httpSession, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(czjrefund,req,model);
        setUserinfoId(model);
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }

        try {
            model.addAttribute("entity", czjrefund);
            Map<String, Object> params = ConvertObj.toMap(czjrefund);
            Pagination pagination = czjrefundService.list(pageNo.intValue(), pageSize.intValue(), params, model);
            model.addAttribute("pagination", pagination);
            return "czjrefund/listdetail";


        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed","获取退款记录表列表失败!"+e.getMessage());
        }
        return "czjrefund/list";
    }
    /** 列表 **/
    @RequestMapping("/list.do")
    public String list(Integer pageNo, Integer pageSize, Czjrefund czjrefund, HttpSession httpSession, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(czjrefund,req,model);
        setUserinfoId(model);
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }


        try {
            Xyuser user = (Xyuser) httpSession.getAttribute("adminuser");
            if (null == user) {

                model.addAttribute("error", "用户为空");
                return "admin/nopermissions";
            } else {
                Czjbusiness czjbusiness = czjbusinessService
                        .getBusinessByTuserid(user.getUserId());// 根据用户ID查询businessid
                if (czjbusiness == null) {
                    return "admin/nopermissions";
                } else {
                    model.addAttribute("entity", czjrefund);
                    czjrefund.setBusinessId(czjbusiness.getId());
                    Map<String, Object> params = ConvertObj.toMap(czjrefund);
                    Pagination pagination = czjrefundService.list(pageNo.intValue(), pageSize.intValue(), params, model);


                    model.addAttribute("pagination", pagination);
                    return "czjrefund/list";


                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed","获取退款记录表列表失败!"+e.getMessage());
        }
        return "czjrefund/list";
    }



    /**
    * api接口退款记录表列表
    * @param pageNo
    * @param pageSize
    * @param czjrefund
    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiList.jn")
    public void apiList(Integer pageNo, Integer pageSize, Czjrefund czjrefund,
        HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        try {
            Map<String, Object> params = ConvertObj.toMap(czjrefund);
            Pagination pagination = czjrefundService.apilist(pageNo.intValue(), pageSize.intValue(), params, model);
            jsonResult(1,"","",pagination,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"","获取退款记录表列表失败!"+e,"",resp);
        }

    }
    /**
    * api接口退款记录表详情
    * @param req
    * @param resp
    * @param model
    * @throws Exception
    */
    @RequestMapping("/apiDetail.jn")
    public void apiDetail(HttpServletRequest req, HttpServletResponse resp,
    ModelMap model) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        Enumeration<String> enumeration = req.getParameterNames();
        if(enumeration.hasMoreElements()){
            String next = enumeration.nextElement();
            params.put(next, req.getParameter(next));
        }

        try {
            Map<String,Object> result = czjrefundService.getApiDetail(params);
            jsonResult(1,"","",result,resp);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult(0,"99","获取退款记录表详情失败!"+e,"",resp);
        }

    }
    /** api测试页面 **/
    @RequestMapping("/apiTest.do")
    public String apiList(HttpServletRequest req, HttpServletResponse resp,
        ModelMap model) throws Exception {
        model.addAttribute("entity",new HashMap<String,Object>());
        return "czjrefund/apiTest";

    }

    /** 保存 **/
    @RequestMapping("/save.do")
    public String save(Czjrefund czjrefund,
                      HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        try {

            if(StringUtils.isNotBlank(czjrefund.getRefundId())){
                czjrefundService.update(czjrefund);


            }else{
                czjrefund.setRefundId(UUIDUtils.getUUID());
                czjrefundService.insert(czjrefund);
            }
            model.addAttribute("success", "保存退款记录表成功");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "保存退款记录表失败!详情："+e.getMessage());
        }
        return "redirect:list.do";
    }


    /** 详情 **/
    @RequestMapping("/detail.do")
    public String detail(@RequestParam(required = true)String refundId,Czjrefund czjrefund, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(czjrefund,req,model);
        setUserinfoId(model);
        try {
            Czjrefund entity = czjrefundService.queryById(czjrefund.getRefundId());
            model.addAttribute("entity", entity);
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", "查询退款记录表出错!详情："+e.getMessage());
        }
        return "czjrefund/detail";
    }
    /** 新增或修改 **/
    @RequestMapping("/add.do")
    public String add(Czjrefund czjrefund, HttpServletRequest req, HttpServletResponse resp,
                       ModelMap model){
        setMsg(czjrefund,req,model);
        setUserinfoId(model);
        if(StringUtils.isNotBlank(czjrefund.getRefundId())){
            czjrefund = czjrefundService.queryById(czjrefund.getRefundId());
            model.addAttribute("entity", czjrefund);
        }
        return "czjrefund/add";
    }
    /** 删除 **/
    @RequestMapping("/delete.do")
    public String delete(@RequestParam(required = true)String refundId,Czjrefund czjrefund, HttpServletRequest req, HttpServletResponse resp,
                     ModelMap model){
        try {
            czjrefundService.deleteById(czjrefund.getRefundId());
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("failed", e.getMessage());
        }
        return "redirect:list.do";
    }
    private void setUserinfoId(ModelMap model) {
        Map<String,Object> param = new HashMap<String,Object>();
        List<Map<String,Object>> listUserinfoId = czjrefundService.getListUserinfoId(param);
        // map.put("name","");
        // map.put("value","");
        model.addAttribute("listUserinfoId", listUserinfoId);
    }

    private void setMsg(Czjrefund czjrefund,HttpServletRequest req, ModelMap model) {
        model.addAttribute("failed", req.getParameter("failed"));
        model.addAttribute("success", req.getParameter("success"));
        model.addAttribute("entity", czjrefund);
    }
    @RequestMapping("/saveBusinContent.do")
    public String saveBusinContent(Czjrefund czjrefund,HttpSession httpSession,HttpServletRequest req, ModelMap model){
        Xyuser user = (Xyuser) httpSession.getAttribute("adminuser");
        if (null == user) {

            model.addAttribute("error", "用户为空");
            return "admin/nopermissions";
        } else {
            Czjbusiness czjbusiness = czjbusinessService
                    .getBusinessByTuserid(user.getUserId());// 根据用户ID查询businessid
            if (czjbusiness == null) {
                return  "admin/nopermissions";
            } else {
                Czjrefund czjrefund2 = czjrefundService.queryById(czjrefund.getRefundId());
                if(czjrefund2.getBusinessId()!=null&&czjrefund2.getBusinessId().equals(czjbusiness.getId())){
                    czjrefundService.update(czjrefund);
                    String orderno = czjrefund2.getOrderCode();
                    List<Czjorder> listorder = czjorderService.getOrderByOrderCode(orderno);
                    //退款成功，订单状态改为已关闭；退款失败，订单状态改为完成
                    for (Czjorder czjorder : listorder) {
                        if(czjrefund.getRefundStatus()==1){
                            try {
                                SecapiPayRefundResult obj = weixininfoService.payRefund(orderno);
//                                czjorder.setStatus(OrderStatus.CLOSE.getIndex());
                                czjorderService.update(czjorder);
                            } catch (Exception e) {
                                e.printStackTrace();
                                log.error("#error:退款失败：",e);
                                model.addAttribute("failed","退款失败");
                            }


                        }else if(czjrefund.getRefundStatus()==2){
                            czjorder.setStatus(OrderStatus.FIN.getIndex());
                            czjorderService.update(czjorder);
                            model.addAttribute("success","退款成功");
                        }
                    }
                    return "redirect:add.do?refundId="+czjrefund.getRefundId();
                }else{
                    return  "admin/nopermissions";
                }


            }

        }



    }


    /**
     * 待发货时，用户退款，商家同意动作
     * @param orderId
     * @param httpSession
     * @param req
     * @param model
     * @return
     */
    @RequestMapping("success.do")
    public String success(@RequestParam String orderId,HttpSession httpSession,
                         HttpServletRequest req, HttpServletResponse resp, ModelMap model) throws Exception {
        try {
            Xyuser user = (Xyuser) httpSession.getAttribute("adminuser");
            if (null == user) {

                model.addAttribute("error", "用户为空");
                return "admin/nopermissions";
            } else {
                Czjbusiness czjbusiness = czjbusinessService
                        .getBusinessByTuserid(user.getUserId());// 根据用户ID查询businessid
                if (czjbusiness == null) {
                    return  "admin/nopermissions";
                } else {
                    Czjorder order = czjorderService.queryById(orderId);
                    if(OrderStatus.CANSEL.getIndex()==order.getStatus()){
                        order.setStatus(OrderStatus.REFUNDED.getIndex());

                        String obj1 = czjrefundService.refundSu(order.getTotalAmount(), order.getOrderCode());
                        if (obj1 != null) return "redirect:/businorder/list?failed="+ URLEncoder.encode(obj1,"UTF-8");
                        if(StringUtils.isNotBlank(order.getCouponsId())){
                            //使用后更改优惠券状态为已使用
                            Czjawarduse czjawarduse32 = new Czjawarduse();
                            czjawarduse32.setAwarduseId(order.getCouponsId());
                            Czjawarduse czjawarduse = czjawarduseService.getCzjawarduse(ConvertObj.toMap(czjawarduse32));
//                            czjawarduse.setStatus(OrderStatus.UNUSE.getIndex());
                            czjawarduseService.updateCzjawarduse(czjawarduse);
                        }

                        czjorderService.update(order);
                        return "redirect:/businorder/list?success="+ URLEncoder.encode("商家退款成功。","UTF-8");
                    }else{

                        return "redirect:/businorder/list?failed="+URLEncoder.encode("用户发起退款时才可以操作！","UTF-8");
    //                    jsonResult(0,"","","用户发起退款时才可以操作",resp);
                    }


                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("#Error:",e);
            return "redirect:/businorder/list?failed="+URLEncoder.encode("退款操作失败！","UTF-8");
        }


    }



    /**
     * 待发货时，用户退款，商家拒绝动作
     * @param orderId
     * @param httpSession
     * @param req
     * @param model
     * @return
     */
    @RequestMapping("refused.do")
    public String refused(@RequestParam String orderId,HttpSession httpSession,
                         HttpServletRequest req, HttpServletResponse resp, ModelMap model) throws Exception {
        try {
            Xyuser user = (Xyuser) httpSession.getAttribute("adminuser");
            if (null == user) {

                model.addAttribute("error", "用户为空");
                return "admin/nopermissions";
            } else {
                Czjbusiness czjbusiness = czjbusinessService
                        .getBusinessByTuserid(user.getUserId());// 根据用户ID查询businessid
                if (czjbusiness == null) {
                    return  "admin/nopermissions";
                } else {
                    Czjorder order = czjorderService.queryById(orderId);
                    if(OrderStatus.CANSEL.getIndex()==order.getStatus()){
                        order.setStatus(OrderStatus.TOSENDGOODS.getIndex());
                        Czjrefund czjrefund = czjrefundService.queryByOrderCode(order.getOrderCode());
                        if(czjrefund==null){
                            return "redirect:/businorder/list?failed="+ URLEncoder.encode("退款记录不存在！","UTF-8");
                        }
                        czjrefund.setUpdatetime(new Date());
                        czjrefund.setRefundStatus(RefundStatus.FAILED.getIndex());

                        czjrefundService.update(czjrefund);

                        czjorderService.update(order);
                        return "redirect:/businorder/list?success="+ URLEncoder.encode("商家拒绝退款成功。","UTF-8");
                    }else{

                        return "redirect:/businorder/list?failed="+URLEncoder.encode("用户发起退款时才可以操作！","UTF-8");
                        //                    jsonResult(0,"","","用户发起退款时才可以操作",resp);
                    }


                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("#Error:",e);
            return "businorder/list?failed="+URLEncoder.encode("退款操作失败！","UTF-8");
        }


    }

    /**
     * 已完成状态，商家退货退款
     * @param orderId
     * @param httpSession
     * @param req
     * @param resp
     * @param model
     * @return
     * @throws Exception
     */
//    @RequestMapping("goods.do")
    public String goods(@RequestParam String orderId,HttpSession httpSession,
                         HttpServletRequest req, HttpServletResponse resp, ModelMap model) throws Exception {
        try {
            Xyuser user = (Xyuser) httpSession.getAttribute("adminuser");
            if (null == user) {

                model.addAttribute("error", "用户为空");
                return "admin/nopermissions";
            } else {
                Czjbusiness czjbusiness = czjbusinessService
                        .getBusinessByTuserid(user.getUserId());// 根据用户ID查询businessid
                if (czjbusiness == null) {
                    return  "admin/nopermissions";
                } else {
                    Czjorder order = czjorderService.queryById(orderId);
                    if(OrderStatus.FIN.getIndex()==order.getStatus()&&(System.currentTimeMillis()-order.getCreateTime().getTime())<7*24*60*60*1000){
//                        order.setStatus(OrderStatus.REFUNDSUCCESS.getIndex());
                        SecapiPayRefundResult obj = weixininfoService.payRefund(order.getOrderCode());
                        if("FAIL".equals(obj.getReturn_code())){

                            return "redirect:/businorder/list?failed="+URLEncoder.encode(obj.getReturn_msg(),"UTF-8");
                        }
                        if("FAIL".equals(obj.getErr_code())){
                            return "redirect:/businorder/list?failed="+URLEncoder.encode(obj.getErr_code_des(),"UTF-8");
                        }
                        Czjrefund czjrefund = czjrefundService.queryByOrderCode(order.getOrderCode());
                        if(czjrefund==null){
                            czjrefund = new Czjrefund();
                        }
                        czjrefund.setCreatetime(new Date());
                        czjrefund.setOrderCode(order.getOrderCode());
                        czjrefund.setRefundAmount(order.getTotalAmount());
                        czjrefund.setUserinfoId(order.getUserinfoId());
                        czjrefund.setRefundStatus(RefundStatus.SUCCESS.getIndex());
                        czjrefund.setBusinessId(order.getBusinessId());
                        czjrefund.setUpdatetime(new Date());
                        czjrefund.setDelFlag(0);
                        if(StringUtils.isBlank(czjrefund.getRefundId())){
                            czjrefund.setRefundId(UUIDUtils.getUUID());
                            czjrefundService.insert(czjrefund);
                        }else{
                            czjrefundService.update(czjrefund);
                        }
                        if(StringUtils.isNotBlank(order.getCouponsId())){
                            //使用后更改优惠券状态为已使用
                            Czjawarduse czjawarduse32 = new Czjawarduse();
                            czjawarduse32.setAwarduseId(order.getCouponsId());
                            Czjawarduse czjawarduse = czjawarduseService.getCzjawarduse(ConvertObj.toMap(czjawarduse32));
//                            czjawarduse.setStatus(OrderStatus.UNUSE.getIndex());
                            czjawarduseService.updateCzjawarduse(czjawarduse);
                        }

                        czjorderService.update(order);
                        return "redirect:/businorder/list?success="+ URLEncoder.encode("商家退货退款成功。","UTF-8");
                    }else{

                        return "redirect:/businorder/list?failed="+URLEncoder.encode("已完成才能进行操作！","UTF-8");
                    }


                }

            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("#Error:",e);
            return "businorder/list?failed="+URLEncoder.encode("退货退款操作失败！","UTF-8");
        }


    }
}
